/**
 * tree：对应树形集合
*/
import tools from "../../../tools"
import HierProperties from "./hierProperties"

export default class hierParentModel {
  constructor(hierProperties = {}, clz) {
    if (!hierProperties.type) {
      hierProperties = clz.tpl()
    }
    this.hierProperties = hierProperties
    this.clz = clz
  }
  static create(hierProperties={}) {
    return new this.clz(hierProperties)
  }
  set(hierProperties) {
    this.hierProperties = hierProperties
  }
  add(item=this.clz.itemTpl()) {
    this.hierProperties.content.push(item)
  }
  insertAfter(index=0, item=this.clz.itemTpl()) {
    this.hierProperties.content.splice(index+1, 0, item)
  }
  delete(key='nodeId', newItem={}) {
    let index = this.hierProperties.content.findIndex(item => item[key] === newItem[key])
    if (index !== -1) {
      this.hierProperties.content.splice(index, 1)
    }
  }
  update(key='nodeId', newItem={}) {
    let index = this.hierProperties.content.findIndex(item => item[key] === newItem[key]);
    if (index !== -1) {
      this.hierProperties.content.splice(index, 1, this.formatItem(newItem))
    }
  }
  find(key='nodeId', value) {
    return this.hierProperties.content.find(item => item[key] === value)
  }
  findNext(value) {
    return this.hierProperties.content.filter(item => item.prev.includes(value))
  }
  findIndex(key='nodeId', value) {
    return this.hierProperties.content.findIndex(item => item[key] === value)
  }
  addProperty(nodeId, tpl=HierProperties.tpl()) {
    let node = this.find('nodeId', nodeId)

    if (node) {
      let hierProperties = HierProperties.create().set(node.properties)
      if (!hierProperties.validName(tpl.name)) {
        hierProperties.add(tpl)
        node.properties = hierProperties.properties
      }
    }
  }
  itemTpl(data = {}) {
    return this.clz.itemTpl(data)
  }
  // 保存前, 格式化content数据
  formatContent() {
  }
  formatItem(item) {
    let newItem = {}
    let itemTpl = hierParentModel.itemTpl()

    Object.keys(itemTpl).forEach(key => {
      newItem[key] = (typeof item[key] === 'undefined') ? itemTpl[key] : item[key]
    })
    return newItem
  }
  static tpl() {
    return {
      type: '',
      content: [
        // item
      ]
    }
  }
  // 添加记录时，初始化的字段表
  static itemTpl() {
    return {
      nodeId: tools.uuid(),
      parentId: "",
      prev: [], //前驱节点
      nodeType: "leaf",  //['root', 'list', 'dictionary', 'leaf']
      name: "新增节点",
      properties: [],
      statusProperties: [],
      link: {
        //指针格式
        type: "",
        className: "",
      },
    }
  }
}